package me.siphone.fragment;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import me.siphone.Constants;
import me.siphone.activity.ContainerActivity;
import me.siphone.adapter.BannerAdapter;
import me.siphone.adapter.StationAdapter;
import me.siphone.http.api.QueryDeviceStatApi;
import me.siphone.http.api.QueryStationApi;
import me.siphone.http.api.QueryTemplateApi;
import me.siphone.http.model.HttpData;
import me.siphone.model.Measurement;
import me.siphone.model.Station;
import org.linphone.R;

public class HomeFragment extends BaseFragment {

    private View view;
    private ViewPager2 viewPager;
    private BannerAdapter bannerAdapter;
    private final Handler handler = new Handler();
    private int currentPosition = 0;

    private RecyclerView stationListView;
    private TextView tvTotalCount;
    private TextView tvOnlineCount;
    private TextView tvBreakdownCount;

    private final Runnable runnable =
            new Runnable() {
                @Override
                public void run() {
                    if (bannerAdapter.getItemCount() == 0) return;
                    currentPosition = (currentPosition + 1) % bannerAdapter.getItemCount();
                    viewPager.setCurrentItem(currentPosition, true);
                    handler.postDelayed(this, 3000); // 3秒切换一次
                }
            };

    private final Timer timer = new Timer();

    @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);

        viewPager = view.findViewById(R.id.viewPager);
        stationListView = view.findViewById(R.id.station_list_simple);
        tvTotalCount = view.findViewById(R.id.tv_total_count);
        tvOnlineCount = view.findViewById(R.id.tv_online_count);
        tvBreakdownCount = view.findViewById(R.id.tv_breakdown_count);

        DisplayMetrics metrics = new DisplayMetrics();
        requireActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int screenHeight = metrics.heightPixels;

        List<Integer> images =
                Arrays.asList(R.drawable.banner1, R.drawable.banner2, R.drawable.banner3);

        bannerAdapter = new BannerAdapter(images);
        viewPager.setAdapter(bannerAdapter);

        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            ViewGroup.LayoutParams params = viewPager.getLayoutParams();
            params.height = screenHeight * 2 / 5;
            viewPager.setLayoutParams(params);
        } else {
            ViewGroup.LayoutParams params = viewPager.getLayoutParams();
            params.height = screenHeight / 3;
            viewPager.setLayoutParams(params);
        }

        // 自动轮播
        handler.postDelayed(runnable, 3000);

        // 手动滑动时同步 currentPosition
        viewPager.registerOnPageChangeCallback(
                new ViewPager2.OnPageChangeCallback() {
                    @Override
                    public void onPageSelected(int position) {
                        currentPosition = position;
                    }
                });

        view.findViewById(R.id.tv_more)
                .setOnClickListener(
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (getResources().getConfiguration().orientation
                                        == Configuration.ORIENTATION_LANDSCAPE) {
                                    getChildFragmentManager()
                                            .beginTransaction()
                                            .replace(R.id.content, new StationListFragment())
                                            .commitNowAllowingStateLoss();
                                } else {
                                    Intent intent =
                                            new Intent(getActivity(), ContainerActivity.class);
                                    intent.putExtra("type", 0);
                                    startActivity(intent);
                                }
                            }
                        });

        view.findViewById(R.id.device_stat)
                .setOnClickListener(
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (getResources().getConfiguration().orientation
                                        == Configuration.ORIENTATION_LANDSCAPE) {
                                    getChildFragmentManager()
                                            .beginTransaction()
                                            .replace(R.id.content, new DeviceListFragment())
                                            .commitNowAllowingStateLoss();
                                } else {
                                    Intent intent =
                                            new Intent(getActivity(), ContainerActivity.class);
                                    intent.putExtra("type", 1);
                                    startActivity(intent);
                                }
                            }
                        });

        queryStationListSimple(true);

        queryDeviceStat();

        queryTemplate();

        startTimer();

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        timer.cancel();
        handler.removeCallbacksAndMessages(null);
    }

    private void startTimer() {
        timer.schedule(
                new TimerTask() {
                    @Override
                    public void run() {
                        if (isResumed()) {
                            Log.d(Constants.TAG, "定时刷新");
                            queryStationListSimple(false);

                            queryDeviceStat();

                            queryTemplate();
                        }
                    }
                },
                3 * 60 * 1000,
                3 * 60 * 1000);
    }

    private void queryStationListSimple(boolean init) {
        EasyHttp.get(this)
                .api(new QueryStationApi())
                .request(
                        new HttpCallbackProxy<HttpData<List<QueryStationApi.Station>>>(this) {
                            @Override
                            public void onHttpSuccess(
                                    @NonNull HttpData<List<QueryStationApi.Station>> result) {
                                super.onHttpSuccess(result);
                                ArrayList<Station> stationList = new ArrayList<>();
                                if (result.getRows() != null && !result.getRows().isEmpty()) {
                                    for (QueryStationApi.Station station : result.getRows()) {
                                        List<QueryStationApi.Station.MonitorData> monitorDataList =
                                                station.getMonitorDataList();
                                        List<Measurement> measurementList = new ArrayList<>();
                                        for (QueryStationApi.Station.MonitorData monitorData :
                                                monitorDataList) {
                                            measurementList.add(
                                                    new Measurement(
                                                            monitorData.getMeasurementStationType(),
                                                            monitorData.getSynchronizeTimeStr(),
                                                            monitorData.getLatestLevel(),
                                                            monitorData.getUnit(),
                                                            monitorData.getStatusFlag()));
                                        }
                                        Station target =
                                                new Station(
                                                        station.getMeasurementStationNo(),
                                                        station.getStationName(),
                                                        measurementList);
                                        stationList.add(target);
                                    }
                                }

                                List<Station> simpleStationList =
                                        stationList.isEmpty()
                                                ? stationList
                                                : stationList.subList(0, 1);
                                stationListView.setLayoutManager(
                                        new LinearLayoutManager(
                                                getContext(), RecyclerView.VERTICAL, false));
                                stationListView.setAdapter(new StationAdapter(simpleStationList));

                                if (getResources().getConfiguration().orientation
                                        == Configuration.ORIENTATION_LANDSCAPE) {

                                    if (init) {
                                        StationListFragment stationListFragment =
                                                new StationListFragment();
                                        Bundle bundle = new Bundle();
                                        bundle.putParcelableArrayList("station_list", stationList);
                                        getChildFragmentManager()
                                                .beginTransaction()
                                                .replace(R.id.content, stationListFragment)
                                                .commitNowAllowingStateLoss();
                                    } else if (getChildFragmentManager().getFragments().size()
                                            > 0) {
                                        Fragment fragment =
                                                getChildFragmentManager().getFragments().get(0);
                                        if (fragment instanceof StationListFragment) {
                                            ((StationListFragment) fragment).update(stationList);
                                        }
                                    }
                                }
                            }
                        });
    }

    private void queryDeviceStat() {
        EasyHttp.get(this)
                .api(new QueryDeviceStatApi())
                .request(
                        new HttpCallbackProxy<QueryDeviceStatApi.Result>(this) {
                            @Override
                            public void onHttpSuccess(@NonNull QueryDeviceStatApi.Result result) {
                                super.onHttpSuccess(result);
                                tvTotalCount.setText(
                                        String.format("设备：%d个", result.getDeviceCount()));
                                tvOnlineCount.setText(
                                        String.format("在线：%d个", result.getDeviceOnline()));
                                tvBreakdownCount.setText(
                                        String.format("故障：%d个", result.getDeviceFault()));
                            }
                        });
    }

    private void queryTemplate() {
        EasyHttp.get(this)
                .api(new QueryTemplateApi())
                .request(
                        new HttpCallbackProxy<Object>(this) {
                            @Override
                            public void onHttpSuccess(@NonNull Object result) {
                                super.onHttpSuccess(result);
                                Map<String, Integer> map = (Map<String, Integer>) result;
                                if (map.keySet().size() > 2) {
                                    String[] keys = map.keySet().toArray(new String[0]);
                                    Integer[] values = map.values().toArray(new Integer[0]);
                                    TextView tvTemplate1 = view.findViewById(R.id.tv_template1);
                                    tvTemplate1.setText(
                                            String.format("%s：%d个", keys[0], values[0]));
                                    TextView tvTemplate2 = view.findViewById(R.id.tv_template2);
                                    tvTemplate2.setText(
                                            String.format("%s：%d个", keys[1], values[1]));
                                    TextView tvTemplate3 = view.findViewById(R.id.tv_template3);
                                    tvTemplate3.setText(
                                            String.format("%s：%d个", keys[2], values[2]));
                                }
                            }
                        });
    }
}
